package edu.friday.controller;
import edu.friday.common.base.BaseController;
import edu.friday.common.result.RestResult;
import edu.friday.common.result.TableDataInfo;
import edu.friday.model.SysUser;
import edu.friday.common.result.Pageable;
import edu.friday.service.SysRoleService;
import edu.friday.service.SysUserService;
import edu.friday.utils.StringUtils;
import org.omg.CORBA.Request;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController //默认在每个方法上加上了@ResponseBody
@RequestMapping("/system/user")
public class SysUserController extends BaseController {

    @Autowired
    SysUserService sysUserService;
    @Autowired
    SysRoleService roleService;
    //这是返回页面，返回数据得加 @ResponseBody
    @GetMapping("/list")
    public TableDataInfo list(SysUser sysUser, Pageable page){
        return sysUserService.selectUserList(sysUser,page);
    }

    /**
     * 批量删除
     * @param userIds
     * @return
     */
    @DeleteMapping("/{userIds}")
    public RestResult remove(@PathVariable Long[] userIds){
        return toAjax(sysUserService.deleteUserByIds(userIds));
    }

    /**
     * 增加用户
     * @param sysUser
     * @return
     */
    @PostMapping
    public RestResult add(@RequestBody SysUser sysUser){
        //校验一下用户是否重复
        if (!sysUserService.checkUserNameUnique(sysUser.getUserName())){
            return RestResult.error("新增用户"+sysUser.getUserName()+"失败");
        }
        //TODO 校验手机号，邮箱

        int i=sysUserService.insertUser(sysUser);
        return toAjax(i);
    }


    /**
     * 修改用户
     * @param user
     * @return
     */
    @PutMapping
    public RestResult edit(@RequestBody SysUser user){
        //TODO验证手机号和邮箱
        user.setUpdateBy("admmin");
        user.setUpdateTime(new Date());
        return toAjax(sysUserService.updateUser(user));
    }


    /**
     * 根据用户编号获取详细信息
     * @param userId
     * @return
     */
    @GetMapping(value = {"/","/{userId}"})
    public RestResult getInfo(@PathVariable(value = "userId",required = false) Long userId){
        RestResult ajax=RestResult.success();
        ajax.put("roles",roleService.selectRoleAll());
        if (StringUtils.isNotNull(userId)){
            ajax.put(RestResult.DATA_TAG,sysUserService.selectUserById(userId));
            ajax.put("roleIds",roleService.selectRoleListByUserId(userId));
        }
        return ajax;
    }
}
